# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:  通过vin抓取整个车型数据, 需要传入品牌, 长安或欧尚

from changanLogin import ChanganLogin
from setting import *
import time, os, json
from untils.requestsTools import requestsTools

class SpiderForVin:

    def __init__(self, brand, vin):
        self.brand=brand
        self.vin=vin
        basePath = os.getcwd() + os.sep + '..' + os.sep + 'changanHtml' + os.sep + 'vinHtml' + os.sep + brand + os.sep + vin
        if not os.path.exists(basePath):
            os.makedirs(basePath)
        self.imgPath = os.getcwd() + os.sep + '..' + os.sep + 'changanImg' + os.sep + 'vinImg' + os.sep + brand + os.sep + vin
        if not os.path.exists(self.imgPath):
            os.makedirs(self.imgPath)
        self.resTools = requestsTools(basePath=basePath)

    def set_headers_cookies(self):
        ca = ChanganLogin(ca_username, ca_password)
        data = ca.login()
        self.cookies = data.get("cookies")
        token = data.get("token")
        self.headers = {}
        self.headers["Host"] = "epc.changan.com.cn:8080"
        self.headers["Accept"] = "*/*"
        self.headers["X-Requested-With"] = "XMLHttpRequest"
        self.headers["Referer"] = "http://epc.changan.com.cn:8080/front/main.html"
        self.headers["Authorization"] = token
        self.resTools.cookies=self.cookies  # 设置必要参数
        self.resTools.headers=self.headers

    def get_timeStr(self, l=13):
        return str(time.time()).replace('.', '.')[:l]

    def searchVin(self):
        vinUrl = '''http://epc.changan.com.cn:8080/record/rcd-vin/selectVinIsExit'''
        params = "?{}={}&{}={}".format("vin", self.vin.upper(), "_", self.get_timeStr())
        url = vinUrl + params
        responseInfo = self.resTools.parseUrl(url=url, fileName=self.vin)
        vinContent = json.loads(responseInfo["content"])
        respCode = vinContent.get("respCode")
        vinData = vinContent.get("data")
        if respCode != "200":
            raise Exception("{} 查询失败".format(self.vin))
        if not vinData.get("scId"):
            raise Exception("{} 不能通过此方式抓取".format(self.vin))
        cid = vinData.get("chexing") + vinData.get("xuanzhuang")
        scName = vinData.get("scName") if vinData.get("scName") else ""
        scId = vinData.get("scId")
        return {"cid": cid, "scName": scName, "scId": scId}

    def get_groupContent_l(self, scid):
        url = 'http://epc.changan.com.cn:8080//oled/epc-tb-partconn/selectSystem'
        params = '?{}={}&{}={}'.format("scId", scid, "_", self.get_timeStr())
        url = url + params
        print("请求主组信息: ", url)
        responseInfo = self.resTools.parseUrl(url, fileName=scid)
        responseContent = json.loads(responseInfo["content"])
        return responseContent.get("data", [])

    def get_strucContent_l(self, scid, systemId):
        url = 'http://epc.changan.com.cn:8080//oled/epc-tb-partconn/selectModule'
        params = '?{}={}&{}={}&{}={}'.format("systemId", systemId, "scId", scid, "_", self.get_timeStr())
        url = url + params
        print("请求分组信息: ", url)
        responseInfo = self.resTools.parseUrl(url, fileName=scid+systemId)
        responseContent = json.loads(responseInfo["content"])
        return responseContent.get("data", [])

    def get_partsContent_l(self, scId, systemId, moduleId, groupnum):
        url = 'http://epc.changan.com.cn:8080//oled/epc-tb-partconn/selectPart'
        params = "?{}={}&{}={}&{}={}&{}={}".format(
                                            "moduleId", moduleId,
                                            "scId", scId,
                                            "systemId", systemId,
                                            "_", self.get_timeStr()
                                                )
        url = url + params
        print("请求零件信息: ", url)
        responseInfo = self.resTools.parseUrl(url, fileName=scId+systemId+moduleId+groupnum)
        responseContent = json.loads(responseInfo["content"])
        return responseContent.get("data", [])

    def get_pdf(self, carCode_fina, moduleCode, pdfName):
        url = 'http://epc.changan.com.cn:8080/front/download/{}.pdf'.format(pdfName)
        print("请求pdf文件: ", url)
        # 获取filePath
        _scidPath = self.imgPath + os.sep + carCode_fina
        if not os.path.exists(_scidPath):
            os.makedirs(_scidPath)
        _modulePath = _scidPath + os.sep + moduleCode  # 分组路径
        if not os.path.exists(_modulePath):
            os.makedirs(_modulePath)
        _pdfPath = _modulePath + os.sep + pdfName + '.pdf'
        if os.path.exists(_pdfPath):
            print("pdf 已存在")
            return
        else:
            pdfResponse = self.resTools.getImg(url)
            if pdfResponse:
                with open(_pdfPath, 'wb') as f:
                    f.write(pdfResponse.content)

    def getData(self, vinInfo):
        scid = vinInfo.get("scId")
        carCode_fina = vinInfo.get("cid")
        groupContent_l = self.get_groupContent_l(scid)
        group_num = 0
        for groupContent in groupContent_l:
            print(groupContent)
            systemId = groupContent.get("id", "")

            # TODO 保存group表
            group_num += 1
            # self.save_group(carCode_fina, group_num, groupContent)

            if not systemId:
                continue
            strucContent_l = self.get_strucContent_l(scid, systemId)
            for strucContent in strucContent_l:
                print(strucContent)
                # TODO 保存struc表
                # self.save_struc(carCode_fina, group_num, strucContent)

                moduleId = strucContent.get("id", "")
                groupnum = strucContent.get("groupnum", "")

                partsContent_l = self.get_partsContent_l(scid, systemId, moduleId, groupnum)
                psort = 0
                for partsContent in partsContent_l:
                    partNum = partsContent.get("partnum", "")
                    compNmCn = partsContent.get("partnameCh", "")
                    psort += 1
                    # self.save_parts(carCode_fina, group_num, groupnum, psort, partsContent)
                    print(partNum, compNmCn)

                if groupnum:
                    pdfName = groupnum
                    self.get_pdf(carCode_fina, groupnum, pdfName)

    def run(self):
        self.set_headers_cookies()
        vinInfo = self.searchVin()
        self.getData(vinInfo)


if __name__ == '__main__':
    pass
#LS5A3ADR1AA500462  SC7133J4.A5
#LS4ADE3R8FF050233  SC6388AV4.H3D1
#LS5A2ABE5FA013338  SC7169B5.C42A
#LS5A3DBE9EA201762
#LS5A2ABE6EA182332  isOld  scid
#LS5A2ABE5FA013484  isOld  scid
#LS4AAB3R0EA549594
#LS4ADE3R8FF050233


